<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-11
 * Time: 11:48
 */

namespace App\Libs\Contracts\PayMent\AliPay;



use App\Libs\Contracts\PayMent\AliPay\Web\pagepay\buildermodel\AlipayTradePagePayContentBuilder;
use App\Libs\Contracts\PayMent\AliPay\Web\pagepay\buildermodel\AlipayTradeRefundContentBuilder;
use App\Libs\Contracts\PayMent\AliPay\Web\pagepay\service\AlipayTradeService;

class AliWeb
{
    public function pay($order)
    {
        $config = getAliConfig();
        //构造参数
        $payRequestBuilder = new AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($order['body']);
	    $payRequestBuilder->setSubject($order['subject']);
	    $payRequestBuilder->setTotalAmount($order['totalFee']/100);
	    $payRequestBuilder->setOutTradeNo($order['orderNo']);

	    $aop = new AlipayTradeService($config);

	   $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);

        return $response;

    }

    public function refund($order)
    {
        $config = getAliConfig();
        $out_trade_no = trim($order['orderNo']);

        //需要退款的金额，该金额不能大于订单金额，必填
        $refund_amount = trim($order['refundPrice']);

        //退款的原因说明
        $refund_reason = trim($order['refundReason']);

        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        $out_request_no = trim($order['refundNo']);

        //构造参数
        $RequestBuilder=new AlipayTradeRefundContentBuilder();
        $RequestBuilder->setOutTradeNo($out_trade_no);
        $RequestBuilder->setRefundAmount($refund_amount);
        $RequestBuilder->setOutRequestNo($out_request_no);
        $RequestBuilder->setRefundReason($refund_reason);

        $aop = new AlipayTradeService($config);

        /**
         * alipay.trade.refund (统一收单交易退款接口)
         * @param $builder 业务参数，使用buildmodel中的对象生成。
         * @return $response 支付宝返回的信息
         */
        $response = $aop->Refund($RequestBuilder);
        dd($response);
        $resultCode = $response->code;
        if(!empty($resultCode)  &&  $resultCode == 10000){
            return true;
        } else {
            throw new \Exception("支付宝退款失败");
        }
    }
}